<?php
namespace BoxEdu\Controller\Home;
//use Think\Controller;

class UserController extends CommonController {

	public function _initialize() {
		//
		//dump(date("Y-m-d H:i:s",1474437988));
		parent::_initialize();
		if ((!$this->user_info['user_id']) && ACTION_NAME != "login" && ACTION_NAME != "index" && ACTION_NAME != "subject") {
			$this->jump("", "/Index/login");
		}
		if ($this->user_id) {
			// $this->ckeck_students_info();
		}
		$this->user_id = $this->user_info['user_id'];
		if ($user_id = I('user_id')) {
			$this->show_user_info = BoxModel("system_member")->load($user_id);
		} else {
			$this->show_user_info = $this->user_info;
		}
		$this->web_title = $this->show_user_info['nickname'] . " - $this->web_title";
		$this->nav_cur = "User";
		$this->user_nav = "Public:user_nav";
	}

	//操作当为空的时候
	public function _empty($name) {
		ob_start();
		$GLOBALS['GETCONTENT'] = 1;
		A("BoxSns/Home/User")->$name();
		$this->user_page_content = ob_get_contents();
		ob_end_clean();
		C('DEFAULT_MODULE', "BoxEdu");
		//dump($this->user_page_content);
		$this->page_content = $this->fetch("User/index");
		$templateFile = $this->getTemplateFile("Index/home");
		parent::display($templateFile);
	}

	//申请奖学金
	public function apply_award_cash() {
		$this->web_title = "申请奖学金 - $this->web_title";
		$this->show_user();
	}

	/*****完善学生信息**/
	public function students_info() {

		//$user_id=$this->user_info['user_id'];
		//$students_info=BoxModel("edu_students")->where(array('user_id'=>$user_id))->find();ß
		$this->province_list = BoxModel("SystemArea")->get("pid=0", "", "id");
		if (IS_POST) {
			$data = I();
			$r = Logic("BoxEdu", "User")->bing_student($data);
			if ($r['msg']) {
				exit(json_encode(array('error' => 1, 'msg' => $r['msg'])));
				//$this->jump($r['msg']);
			} else {
				exit(json_encode(array('error' => 0, 'msg' => '信息保存成功')));
				//$this->jump("信息保存成功", U('index'));
			}
		}
		$this->show_user();
	}

	public function agreement() {
		if (IS_POST) {
			$user_id = $this->user_info['user_id'];
			$r = BoxModel("edu_user")->where(array('user_id' => $user_id))->save(array('agreement' => 1));
			exit(json_encode(array('error' => 0, 'msg' => '保存成功')));
		}
	}

	public function index() {

		if ($user_id = I('user_id')) {
			$this->user_nav = "Public:user_nav_vis";
			$this->_user_id = $user_id;
			Logic("BoxEdu", "User")->visit($user_id);
		} else {
			$this->_user_id = $this->user_id;
			if (!$this->user_id) {
				$this->jump("", "/Index/login");
			}
		}
		if ($this->user_info['user_id']) {
			$msg_count = BoxModel("sns_notification_count")->get(array('user_id' => $this->user_info['user_id']));
			$this->comment_count = $msg_count['comment'];
		}
		if ($this->is_mobile && !I('user_id') && !I('timeline')) {

			$this->display("User/index-wap");
		} else {
			$tpl = "User/index_vis";
			$this->show_user($tpl);
		}
	}

	public function my_subject() {
		$data = $this->user_info['subjectids_info'];
		foreach ($data as $k => $one) {
			$subjectid = $one['subjectid'];
			$data[$k]['comment_str'] = $r['error'] == 0 ? "学员心声" : "评论";
			if ($one['type'] == 2) {
				$data[$k]['type_str'] = "试听";
			} elseif ($one['type'] == 1) {
				$data[$k]['type_str'] = "进入班级";
			} else {
				$data[$k]['type_str'] = "开通课程";
			}
			if ($one['end_date'] < date("Y-m-d")) {
				$data[$k]['end'] = 1;
			}
			$subs[] = $one['subjectid'];
		}
		//dump($data);
		$this->data = $data;

		$sub_exp = trim(implode(",", $subs));
		$this->list = BoxModel("EduSubject")->get("subjectid not in($sub_exp)");
		$this->show_user();
	}

	/***我的答题数**/
	public function ask_num() {

		$this->web_title = "提问数 - $this->web_title";
		$this->type = I('type', "all");
		// dump( $this->type);
		$where['type'] = 'ask_num';
		$where['user_id'] = $this->user_info['user_id'];
		if ($this->type == "in") {
			$where['num'] = array('gt', "0");
		}
		if ($this->type == "out") {
			$where['num'] = array('lt', "0");
		}
		if ($this->start_time = I('start_time')) {
			$where['add_date'][] = array('gt', $this->start_time);
		}
		if ($this->end_time = I('end_time')) {
			$where['add_date'][] = array('lt', $this->end_time);
		}
		$this->where = $where;
		$this->Sum = BoxModel("system_log")->where($where)->sum("num");
		$this->Sum = $this->Sum ? $this->Sum : 0;
		$this->show_user();
	}

	/***购买答题数**/
	public function buy_ask_num() {
		$setting = dict("setting");
		foreach ($setting['Cardtime'] as $one) {
			$ask_array[$one['l']] = $one['r'];
		}

		$this->ask_array = $ask_array;
		if (IS_POST) {
			//$this->payment_id = 44;
			$this->num = I('num');
			$this->yie = I('yie');
			$this->goods_amount = $this->ask_array[$this->num];
			if (!($this->goods_amount > 0)) {

				exit(json_encode(array('error' => 1, 'msg' => '请选择充值卡次数')));
			}
			$row = array(
				//  'payment_id' => 44,
				'goods_amount' => $this->goods_amount,
				'yie' => $this->yie,
				'num' => $this->num,
			);
			$r = Logic("BoxEdu", "User")->buy_ask_num($row);
			exit(json_encode($r));

		}
		$this->show_user();
	}

	//申请成功代理
	public function apply_agent() {
		$school_id = $this->user_info['school_id'];
		$now = time();
		$data = BoxModel("edu_user")->where(array('user_id' => $this->user_id))->find();
		if (!$data['school_num']) {
			$this->jump("请先开通课程");
		}
		$list = BoxModel("edu_user_agent_apply")->get("school_id='$school_id' and status in (1,2)");
		foreach ($list as $k => $one) {
			if ($one['expirationTime'] > 0 && $one['expirationTime'] < $now) {
				unset($list[$k]);
			}

		}
		$count = count($list);
		$shool_info = BoxModel("edu_schools")->where("id='$school_id'")->find();
		$agentLimit = $shool_info['agentLimit'];
		if ($count > $agentLimit || $count == $agentLimit) {
			$this->jump("对不起，你来晚了，代理招满");
		}
		$apply = BoxModel("edu_user_agent_apply")->where("user_id='$this->user_id'")->find();
		$user_info = $this->user_info;
		unset($user_info['id']);
		unset($user_info['status']);
		unset($user_info['remark']);
		unset($user_info['agreement']);
		if ($apply['id']) {
			$apply = BoxModel("edu_user_agent_apply")->load($apply['id']);
			if ($apply && ($apply['status'] == 1 || $apply['status'] == 2)) {
				$this->from_id = "apply_apply_agent";
			}
		}
		$apply['school_name'] = $user_info['school_name'];
		$apply = array_merge($user_info, (array) $apply);
		$this->apply = $apply;
		if (IS_POST) {
			BoxModel("edu_user_agent_apply")->where("user_id='$this->user_id'")->delete();
			$row = array(
				'user_id' => $this->user_id,
				'updatetime' => time(),
				'status' => 1,
				'school_id' => $school_id,
				'add_time' => date("Y-m-d H:i:s"),
				'content' => stripslashes(htmlspecialchars_decode(I('content'))),
				'phone' => I('phone'),
				'name' => I('name'),
			);
			$data = I();
			$info = $this->_upload();
			//	dump($info);exit();
			if (is_array($info)) {
				foreach ($info as $k => $one) {
					$data[$k] = array(
						'file_url' => $one['savepath'] . $one['savename'],
						'file_name' => $one['name'],
					);
				}
			}
			$row['moreFields'] = serialize(array_diff($data, $row));
			$r = BoxModel("edu_user_agent_apply")->add($row);
			exit(json_encode(array('falg' => 0, 'msg' => '申请提交成功，请等待管理员审核')));
		}
		$this->display();
	}

	//申请奖金学
	public function apply_scholarship() {
		$this->subjectid = $subjectid = I('subjectid');
		$apply = BoxModel("edu_user_scholarship")->where("user_id='$this->user_id' and subject_id='$subjectid'")->find();
		//dump("user_id='$this->user_id' and subject_id='$subjectid'");exit();
		$user_info = $this->user_info;
		unset($user_info['id']);
		unset($user_info['status']);
		unset($user_info['remark']);
		if ($apply['id']) {
			$apply = BoxModel("edu_user_scholarship")->load($apply['id']);
		}
		$apply = array_merge($user_info, (array) $apply);
		$this->apply = $apply;
		if (IS_POST) {
			BoxModel("edu_user_scholarship")->where("user_id='$this->user_id' and subject_id='$subjectid'")->delete();
			$subjectInfo = BoxModel("edu_subject")->where(array('subjectid' => $subjectid))->find();
			$class_id = $subjectInfo['subject_class'];
			$row = array(
				'subject_id' => $subjectid,
				'user_id' => $this->user_id,
				'class_id' => $class_id,
				'updatetime' => time(),
				'status' => 1,
				'add_time' => date("Y-m-d H:i:s"),
				'phone' => I('phone'),
				'name' => I('name'),
				// 'content' => stripslashes(htmlspecialchars_decode(I('content'))),
			);
			$data = I();
			$info = $this->_upload();
			if (is_array($info)) {
				foreach ($info as $k => $one) {
					$data[$k] = array(
						'file_url' => $one['savepath'] . $one['savename'],
						'file_name' => $one['name'],
					);
				}
			}
			$row['moreFields'] = serialize(array_diff($data, $row));
			$r = BoxModel("edu_user_scholarship")->add($row);
			//exit(json_encode(array('falg'=>0,'msg'=>'申请提交成功，请等待管理员审核')));
			$this->jump('申请提交成功，请等待管理员审核');
		}
		$this->show_user();
	}

	/******申请重学****/
	public function apply_relearn() {
		$this->subjectid = $subjectid = I('subjectid');
		$apply = BoxModel("edu_user_relearn_apply")->where("user_id='$this->user_id' and subject_id='$subjectid'")->find();
		if ($apply['id']) {
			$apply = BoxModel("edu_user_relearn_apply")->load($apply['id']);
		}
		$user_info = $this->user_info;
		unset($user_info['id']);
		unset($user_info['status']);
		unset($user_info['remark']);
		$apply = array_merge($user_info, (array) $apply);
		$this->apply = $apply;
		if (IS_POST) {
			BoxModel("edu_user_relearn_apply")->where("user_id='$this->user_id' and subject_id='$subjectid'")->delete();
			$row = array(
				'subject_id' => $subjectid,
				'user_id' => $this->user_id,
				'updatetime' => time(),
				'status' => 1,
				'add_time' => date("Y-m-d H:i:s"),
				'phone' => I('phone'),
				'name' => I('name'),
				// 'moreFields' => serialize(I()),
				//   'content' => stripslashes(htmlspecialchars_decode(I('content'))),
			);
			$data = I();
			$info = $this->_upload();
			if (is_array($info)) {
				foreach ($info as $k => $one) {
					$data[$k] = array(
						'file_url' => $one['savepath'] . $one['savename'],
						'file_name' => $one['name'],
					);
				}
			}
			$row['moreFields'] = serialize(array_diff($data, $row));
			$r = BoxModel("edu_user_relearn_apply")->add($row);
			$this->jump('申请提交成功，请等待管理员审核');
			//exit(json_encode(array('falg'=>0,'msg'=>'申请提交成功，请等待管理员审核')));
		}
		$this->show_user();
	}

	/************上传base64图片********************/
	function uploadImgFrom_base64() {
		$base64 = I('formFile');
		$IMG = base64_decode($base64);
		$newdir = UploadPath . "User/" . date("Ymd");
		mk_dir($newdir);
		$picname = md5(uniqid(rand()));
		$tureUrl = $newdir . "/" . $picname . ".jpg";
		$r = file_put_contents($tureUrl, $IMG);
		if ($r) {
			$b_pic = ImgDomain . "/User/" . date("Ymd") . "/" . $picname . ".jpg";
			echo $b_pic;
		} else {
			echo 0;
		}
	}

	/*****添加学员心声**/
	public function add_comment_subject_order() {
		$this->subjectid = I('subjectid');
		$subjectid = $row['subjectid'];
		$data = BoxModel("EduSubjectOrder")->where("user_id='$this->user_id' and subjectid='$this->subjectid'")->find();
		if ($data['status'] == 4) {
			$this->jump("", U("Index/xueyuan", array('subjectid' => $this->subjectid)));
			exit();
		}
		if (IS_AJAX) {
			$row = array(
				'content' => I('content'),
				'subjectid' => I('subjectid'),
			);
			$data = Logic("BoxEdu", "User")->add_comment_subject_order($row);
			echo json_encode($data);
			exit();
		}
		$this->show_user();
	}

	/******取消选座记录****/
	public function cancel_book_class() {
		$id = I('id');
		$model = BoxModel('edu_classrooms_book');
		$r = $model->where("id='$id'")->delete();
		$this->jump("取消成功");
	}

	//收藏一道题
	public function collect_questions() {
		$questions_id = I('qid');
		$row = array(
			'questions_id' => $questions_id,
			'exams_id' => I('exams_id'),
			'type' => 'favorite',
		);
		$r = Logic("BoxEdu", "User")->collect_questions($row);
		echo $r;
	}

	public function del_collect_questions() {
		$questions_id = I('qid');
		$row = array(
			'questions_id' => $questions_id,
			'type' => 'wrong',
			'user_id' => $this->user_info['user_id'],
		);
		$model = BoxModel("edu_questions_user");
		$Rf = $model->where($row)->delete();
		echo $Rf;

	}

	//赚学币
	public function earn() {
		// dump($this->user_info);
		$this->web_title = "赚学币 - $this->web_title";
		if ($this->user_info['is_agent']) {
			$this->invit_count = (int) BoxModel("edu_user")->where(array('agent_pid' => $this->user_info['user_id']))->count(); //邀请好友注册
		} else {
			$this->invit_count = (int) BoxModel("edu_user")->where(array('school_pid' => $this->user_info['user_id']))->count(); //邀请好友注册
		}
		$this->invit_money = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00008'))->sum("num"); //累计赚取现金
		$this->comment_all = (int) BoxModel("sns_comment")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'EduAsk'))->count();
		$this->comment_best = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00004'))->count();
		$this->comment_money = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00004'))->sum("num"); //累计赚取现金

		$school_id = $this->user_info['school_id'];
		$now = time();
		$list = (array) BoxModel("edu_user_agent_apply")->get("school_id='$school_id' and status in (1,2)");
		foreach ($list as $k => $one) {
			if ($one['expirationTime'] > 0 && $one['expirationTime'] < $now) {
				unset($list[$k]);
			}

		}
		$count = count($list);
		$shool_info = BoxModel("edu_schools")->where("id='$school_id'")->find();
		$this->agentLimit = $shool_info['agentLimit'] - $count;
		$this->show_user();
	}

	//赚学币
	public function modal_earn() {
		// dump($this->user_info);
		$user_info = BoxModel("edu_user")->where(array('user_id' => $this->user_info['user_id']))->find();
		$modal_earn_hit = $user_info['modal_earn_hit'];
		if ($user_info['modal_earn_hit'] < 5) {
			BoxModel("edu_user")->where(array('user_id' => $this->user_info['user_id']))->save(array('modal_earn_hit' => $modal_earn_hit + 1));
		} else {
			$this->modal_earn_show = 2;
		}
		$this->web_title = "赚学币 - $this->web_title";
		if ($this->user_info['is_agent']) {
			$this->invit_count = (int) BoxModel("edu_user")->where(array('agent_pid' => $this->user_info['user_id']))->count(); //邀请好友注册
		} else {
			$this->invit_count = (int) BoxModel("edu_user")->where(array('school_pid' => $this->user_info['user_id']))->count(); //邀请好友注册
		}
		$this->invit_money = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00008'))->sum("num"); //累计赚取现金

		$school_id = $this->user_info['school_id'];
		$now = time();
		$count = BoxModel("edu_user_agent_apply")->where("school_id='$school_id' and status in (1,2) and expirationTime>$now")->count();
		$shool_info = BoxModel("edu_schools")->where("id='$school_id'")->find();
		$this->agentLimit = $shool_info['agentLimit'] - $count;
		$this->show_user();
	}

	//赚学币
	public function modal_earn_2() {
		// dump($this->user_info);
		$user_info = BoxModel("edu_user")->where(array('user_id' => $this->user_info['user_id']))->find();
		$modal_earn_hit = $user_info['modal_earn_hit_2'];
		if ($modal_earn_hit < 5) {
			BoxModel("edu_user")->where(array('user_id' => $this->user_info['user_id']))->save(array('modal_earn_hit_2' => $modal_earn_hit + 1));
		} else {
			$this->modal_earn_show = 2;
		}
		$this->comment_all = (int) BoxModel("sns_comment")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'EduAsk'))->count();
		$this->comment_best = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00004'))->count();
		$this->comment_money = (int) BoxModel("system_log")->where(array('user_id' => $this->user_info['user_id'], 'type' => 'money', 'event' => '00004'))->sum("num"); //累计赚取现金

		$school_id = $this->user_info['school_id'];
		$now = time();
		$count = BoxModel("edu_user_agent_apply")->where("school_id='$school_id' and status in (1,2) and expirationTime>$now")->count();
		$shool_info = BoxModel("edu_schools")->where("id='$school_id'")->find();
		$this->agentLimit = $shool_info['agentLimit'] - $count;
		$this->show_user();
	}

	/***我的班级*/
	public function subject() {
		$this->show_user();
	}

	//退出代理
	public function quitAgent() {
		$data = BoxModel("edu_user_agent_apply")->where(array('user_id' => $this->user_info['user_id']))->find();
		if ($data['status'] == 2 && $data['expirationTime'] > time()) {
			BoxModel("edu_user_agent_apply")->where(array('id' => $data['id']))->save(array('status' => 4));
			BoxModel("edu_user")->where(array('user_id' => $this->user_info['user_id']))->save(array('is_agent' => 0));
			exit(json_encode(array('error' => 0, 'msg' => '成功退出校园合伙人')));
		} else {
			exit(json_encode(array('error' => 0, 'msg' => '您当前身份不是校园合伙人，无权操作')));
			// $this->jump("您当前身份不是校园合伙人，无权操作");
		}
	}

	//领取待激活学币
	public function get_frozen_capital() {
		$id = I('id', "0", "intval");
		$data = BoxModel("edu_red_packets")->where(array('id' => $id))->find();
		if ($data['user_id'] != $this->user_id) {
			echo json_encode(array('error' => 2, 'msg' => '非法操作'));
			exit();
		}
		if ($data['user_id'] == $this->user_id && $data['status'] == 1) {
			$num = $data['num'];
			BoxModel("edu_red_packets")->where(array('id' => $id))->save(array('status' => 2));
			BoxModel("edu_user")->where(array('user_id' => $this->user_id))->setInc("frozen_capital", $num);
			echo json_encode(array('error' => 0, 'msg' => '领取成功'));
		} elseif ($data['status'] != 1) {
			echo json_encode(array('error' => 1, 'msg' => '当前状态不可领取'));
		}

	}
//领取学习卡
	public function get_study_cards() {
		$code = I('code');
		$model = BoxModel("edu_study_cards");
		$this->data = $model->where(array('code' => $code))->find();
		//dump($model);exit();
		if (!$this->data) {
			$this->error = "链接已失效";
			//$this->error("");
		}
		if ($this->data['exp_time'] < date("Y-m-d")) {
			$this->error = "学习卡过期";
		}
		if ($this->data['limit_num'] < 1) {
			$this->error = "学习卡已被领取完毕";
		}
		$user_has_cards = BoxModel("edu_study_cards_user")->where(array('card_code' => $code, 'user_id' => $this->user_id))->find();
		if ($user_has_cards) {
			$this->error = "已领取";
		}
		if (IS_POST) {
			if ($this->error) {
				exit(json_encode(array('error' => 1, 'msg' => $this->error)));
			}
			$model->startTrans();
			$row = array(
				'user_id' => $this->user_id,
				'card_code' => $code,
				'addtime' => time(),
			);
			$r = BoxModel("edu_study_cards_user")->add($row);
			$r2 = $model->where(array('code' => $code))->setDec("limit_num");
			//dump($model);
			if ($r && $r2) {
				$model->commit();
				exit(json_encode(array('error' => 0, 'msg' => '领取成功')));
			} else {
				$model->rollback();
				exit(json_encode(array('error' => 2, 'msg' => '系统错误，请稍后再试')));
			}

		}
		$this->display();
	}

}